package com.yougou.ui.cart;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.yougou.R;
import com.yougou.data.model.CartItem;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class CartCheckoutAdapter extends RecyclerView.Adapter<CartCheckoutAdapter.ViewHolder> {
    
    private List<CartItem> mDataList = new ArrayList<>();
    
    public void setData(List<CartItem> dataList) {
        if (dataList != null) {
            mDataList = dataList;
            notifyDataSetChanged();
        }
    }
    
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_checkout_goods, parent, false);
        return new ViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        CartItem item = mDataList.get(position);
        
        // 商品图片
        String imageUrl = item.getGoods().getGoodsPic();
        if (imageUrl != null && !imageUrl.isEmpty()) {
            Glide.with(holder.itemView.getContext())
                    .load(imageUrl)
                    .placeholder(R.drawable.placeholder_image)
                    .error(R.drawable.placeholder_image)
                    .into(holder.ivGoodsImage);
        }
        
        // 商品名称
        holder.tvGoodsName.setText(item.getGoods().getGoodsName());
        
        // 商品价格
        holder.tvGoodsPrice.setText(String.format(Locale.CHINA, "¥%.2f", item.getGoods().getGoodsPrice()));
        
        // 商品数量
        holder.tvQuantity.setText("x" + item.getQuantity());
        
        // 小计
        holder.tvSubtotal.setText(String.format(Locale.CHINA, "¥%.2f", item.getSubtotal()));
    }
    
    @Override
    public int getItemCount() {
        return mDataList.size();
    }
    
    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivGoodsImage;
        TextView tvGoodsName;
        TextView tvGoodsPrice;
        TextView tvQuantity;
        TextView tvSubtotal;
        
        ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivGoodsImage = itemView.findViewById(R.id.iv_goods_image);
            tvGoodsName = itemView.findViewById(R.id.tv_goods_name);
            tvGoodsPrice = itemView.findViewById(R.id.tv_goods_price);
            tvQuantity = itemView.findViewById(R.id.tv_quantity);
            tvSubtotal = itemView.findViewById(R.id.tv_subtotal);
        }
    }
}

